import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../UserInfo/user_info_entity.dart';
import '../global_store/store.dart';

Reducer<GlobalState> buildReducer() {
  return asReducer(
    <Object, Reducer<GlobalState>>{
      GlobalAction.UserLogin: _onUserLogin,
      GlobalAction.UserLogout: _onUserLogout,
      GlobalAction.onAction: _onAction,
    },
  );
}

GlobalState _onUserLogin(GlobalState state, Action action) {
  UserInfoEntity info = action.payload;
  info.save();
  return state.clone()..userInfo = info;
}

GlobalState _onUserLogout(GlobalState state, Action action) {
  UserInfoEntity info = UserInfoEntity();
  info.logout();
  return state.clone()..userInfo = info;
}

GlobalState _onAction(GlobalState state, Action action) {
  GlobalState newState = GlobalState();
  newState.userInfo = UserInfoEntity.fromJson(state.userInfo.toJson());
  return newState;
}
